package com.akkainaction.tool.io.tcp.client;

import akka.actor.ActorRef;
import akka.actor.Props;
import akka.actor.UntypedActor;
import akka.io.Tcp;
import akka.io.TcpMessage;
import akka.util.ByteString;

import java.net.InetSocketAddress;

public class TcpClientDemo extends UntypedActor {
    ActorRef conn;
    @Override
    public void preStart() throws Exception {
        ActorRef tcp = Tcp.get(getContext().system()).manager();
        InetSocketAddress address = new InetSocketAddress("127.0.0.1", 1234);
        tcp.tell(TcpMessage.connect(address), getSelf());
    }

    @Override
    public void onReceive(Object msg) throws Exception {
        System.out.println(getSelf() + "接收到消息:[" + msg + "]");
        if (msg instanceof Tcp.Connected) {
            conn = getSender();
            ActorRef clientHandler = getContext().actorOf(Props.create(ClientHandler.class), "clientHandler");
            conn.tell(TcpMessage.register(clientHandler), getSelf());
            conn.tell(TcpMessage.write(ByteString.fromString("HelloAkka")), getSelf());
        } else {
            if(conn != null){
                conn.tell(msg,getSelf());
            }
        }
    }
}
